package com.fbinggun.fattribute.status;
import com.alibaba.fastjson.JSONObject;
import com.fbinggun.fattribute.attribute.IAttribute;
import org.bukkit.plugin.Plugin;
import java.util.HashMap;
import java.util.Map;

public class StatusMap  {

    Map<String,Modifier> modifierMap= new HashMap<>();

    public JSONObject toJson(){
        JSONObject jsonObject= new JSONObject();
        if(modifierMap.size()==0){
            return null;
        }
        for(Modifier modifier: modifierMap.values()){
            jsonObject.put(modifier.getKey(),modifier.toJson());
        }
        return jsonObject;
    }
    public StatusMap(){

    }
    public StatusMap(JSONObject json){
        for(String key:json.keySet()){
            JSONObject jsonModifier =json.getJSONObject(key);
            modifierMap.put(key,new Modifier(jsonModifier));
        }
    }

    public Map<IAttribute,Double> getAttributeMap() {
        if (modifierMap == null||modifierMap.size()==0) {
            return null;
        }
        Map<IAttribute,Double> attributeDoubleMap = new HashMap<>();
        for (Modifier modifier : modifierMap.values()) {
            if(modifier.getAttribute()!=null&&modifier.getAttribute().size()!=0){
            for (IAttribute attribute : modifier.getAttribute().keySet()) {
                Double yVlue =attributeDoubleMap.get(attribute);
                Double value = modifier.getAttribute().get(attribute);
                if(yVlue==null){
                    attributeDoubleMap.put(attribute,value);
                }else {
                    attributeDoubleMap.put(attribute,value+yVlue);
                }
            }}
        }
        return attributeDoubleMap;
    }


    public Double getVlues(String key){
        Map<IAttribute,Double> attributeDoubleMap = getAttributeMap();
        if(attributeDoubleMap==null){
            return 0d;
        }
        if(attributeDoubleMap.get(IAttribute.getKey(key))==null){
            return 0d;
        }
        return Math.max(attributeDoubleMap.get(IAttribute.getKey(key)),0);
    }

    public void removeModifier(String key){
        modifierMap.remove(key);
    }
    public void removeModifier(Plugin plugin){
        if (modifierMap == null) {
            return;
        }
        for (Modifier modifier : modifierMap.values()) {
            if(modifier.getPlugin().equalsIgnoreCase(plugin.getName())){
                modifierMap.remove(modifier.getKey());
            }
        }
    }


    public void addModifier(Modifier modifier){
        if(modifier!=null){
            modifierMap.put(modifier.getKey(),modifier);
        }
    }


}
